<template>
  <a-drawer
      :title="detail.village_name + '-预存项设置'"
      :maskClosable="false"
      :visible="visible"
      :width="400"
      :body-style="{
      paddingBottom: '80px',
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
      overflowY: 'auto',
    }"
      @close="onCancel"
  >
    <a-form layout="vertical">
      <a-row :gutter="[12, 0]" :wrap="true">
        <a-col :span="24">
          <a-form-item style="margin-bottom: 10px">
            <template #label>
              <span>租客可选充值项</span>
            </template>
            <a-tag
                v-for="(item, index) of modelRef.recharge_item"
                :key="item"
                color="cyan"
                :closable="true"
                @close="onChargeItemRemove(index)"
                style="margin-bottom: 12px"
            >
              <span>{{ item }}</span>
            </a-tag>
            <a-popover
                title="新建可选充值项"
                trigger="click"
                v-model:visible="addVisible"
                placement="topLeft"
            >
              <template #content>
                <a-row :gutter="12" align="middle">
                  <a-col>金额：</a-col>
                  <a-col>
                    <a-input-number
                        :min="0"
                        :precision="2"
                        v-model:value="addValue"
                        placeholder="请输入"
                        style="width: 200px"
                    />
                  </a-col>
                </a-row>
                <div style="margin-top: 20px; height: 40px">
                  <div style="float: right">
                    <a-space>
                      <a-button @click="addVisible = false"> 取消</a-button>
                      <a-button
                          type="primary"
                          @click="addConfirm"
                          :disabled="!addValue"
                      >
                        确定
                      </a-button>
                    </a-space>
                  </div>
                </div>
              </template>
              <a-tag style="cursor: pointer">
                <PlusOutlined/>
                充值项
              </a-tag>
            </a-popover>
          </a-form-item>
        </a-col>


        <a-checkbox style="padding: 0 6px" v-model:checked="modelRef.can_customize">开启租客自定义金额充值
        </a-checkbox>

        <!--        <a-col :span="24">-->
        <!--          <div>-->
        <!--              <span class="becurrent">-->
        <!--                <span class="color:#4f70e9">通用预存 </span>-->
        <!--                <a-tooltip>-->
        <!--                  <template #title-->
        <!--                  >可以用于除专项费用类型之外的其他缴费账单。</template-->
        <!--                  >-->
        <!--                  <QuestionCircleOutlined/>-->
        <!--                </a-tooltip>-->
        <!--              </span>-->
        <!--            <div style="padding: 15px 15px 30px 15px; background-color: #ececec">-->
        <!--              <a-form-item>-->
        <!--                <template #label>-->
        <!--                  <span>是否开启</span>-->
        <!--                </template>-->
        <!--                <a-switch-->
        <!--                    :checked="common_charge"-->
        <!--                    checked-children="开"-->
        <!--                    un-checked-children="关"-->
        <!--                    :checked-value="1"-->
        <!--                    :un-checked-value="0"-->
        <!--                    @change="(val) => StatusChanges(val)"-->
        <!--                />-->
        <!--              </a-form-item>-->
        <!--              <a-form-item>-->
        <!--                <template #label>-->
        <!--                  <span>自动缴费项目</span>-->
        <!--                  <a-tooltip>-->
        <!--                    <template #title>租客可选的支持自动缴费的项目类型</template>-->
        <!--                    <QuestionCircleOutlined/>-->
        <!--                  </a-tooltip>-->
        <!--                </template>-->
        <!--                <a-tag-->
        <!--                    closable-->
        <!--                    color="blue"-->
        <!--                    style="height: 24px; border-radius: 6px; margin-bottom: 8px"-->
        <!--                    v-for="(tagItem, tagIndex) of tagList"-->
        <!--                    :key="tagIndex"-->
        <!--                    @close.prevent="removeCostType(tagItem, tagIndex)"-->
        <!--                >{{ tagItem.label }}-->
        <!--                </a-tag-->
        <!--                >-->
        <!--                <a-popover-->
        <!--                    title="添加费用类型"-->
        <!--                    trigger="click"-->
        <!--                    v-model:visible="addCostVisible"-->
        <!--                    placement="topLeft"-->
        <!--                    style="width: 200px"-->
        <!--                >-->
        <!--                  <template #content>-->
        <!--                    <a-cascader-->
        <!--                        v-model:value="modelRef.cost_types"-->
        <!--                        :options="costTypeList"-->
        <!--                        :load-data="getCostTypeSub"-->
        <!--                        placeholder="添加费用类型"-->
        <!--                        dropdownClassName="fee-type-cascader-custom"-->
        <!--                        @change="onCostTypeChange"-->
        <!--                    />-->
        <!--                  </template>-->
        <!--                  <a-tag style="cursor: pointer">-->
        <!--                    <PlusOutlined/>-->
        <!--                    费用类型-->
        <!--                  </a-tag>-->
        <!--                </a-popover>-->
        <!--              </a-form-item>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--        </a-col>-->

        <!--        <a-col :span="24">-->
        <!--          <div>-->
        <!--            <span class="becurrent">-->
        <!--              <span class="color:#4f70e9">专项预存 </span>-->
        <!--              <a-tooltip>-->
        <!--                <template-->
        <!--                    #title>只能用于对应充值费用类型的缴费账单,不可用于其他类型缴费账单。</template>-->
        <!--                <QuestionCircleOutlined/>-->
        <!--              </a-tooltip>-->
        <!--            </span>-->
        <!--            <div style="padding: 15px 15px 30px 15px; background-color: #ececec">-->
        <!--              <a-form-item>-->
        <!--                <template #label>-->
        <!--                  <span>是否开启</span>-->
        <!--                </template>-->
        <!--                <a-switch-->
        <!--                    :checked="text"-->
        <!--                    checked-children="开"-->
        <!--                    un-checked-children="关"-->
        <!--                    :checked-value="1"-->
        <!--                    :un-checked-value="0"-->
        <!--                    @change="(val) => StatusChange(val)"-->
        <!--                />-->
        <!--              </a-form-item>-->
        <!--              <a-form-item>-->
        <!--                <template #label>-->
        <!--                  专项预存费用类型-->
        <!--                  <a-tooltip>-->
        <!--                    <template #title-->
        <!--                    >租客可正对某一种类型费用进行专项充值，并且只能用于该费用类型的账单。<br/>-->
        <!--                      专项预存费用将会自动扣款，且用户无法手动关闭这些费用类型的自动缴费。-->
        <!--                    </template-->
        <!--                    >-->
        <!--                    <QuestionCircleOutlined/>-->
        <!--                  </a-tooltip>-->
        <!--                </template>-->
        <!--                <a-tag-->
        <!--                    closable-->
        <!--                    color="orange"-->
        <!--                    style="-->
        <!--                        height: 24px;-->
        <!--                        border-radius: 6px;-->
        <!--                        margin-bottom: 8px;-->
        <!--                      "-->
        <!--                    v-for="(tagItem, tagIndex) of xiangmlist"-->
        <!--                    :key="tagIndex"-->
        <!--                    @close.prevent="removeCost(tagItem, tagIndex)"-->
        <!--                >{{ tagItem.label }}-->
        <!--                </a-tag-->
        <!--                >-->
        <!--                <a-cascader-->
        <!--                    :disabled="!text"-->
        <!--                    style="width: 100%"-->
        <!--                    v-model:value="cost_list"-->
        <!--                    :options="costTypeList"-->
        <!--                    :load-data="getCostTypeSub"-->
        <!--                    placeholder="添加专项预存项目"-->
        <!--                    dropdownClassName="fee-type-cascader-custom"-->
        <!--                    @change="TypeChange"-->
        <!--                />-->
        <!--              </a-form-item>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--        </a-col>-->
      </a-row>
    </a-form>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onCancel"> 取消</a-button>
        <a-button type="primary" @click.prevent="onSubmit"> 确定</a-button>
      </a-space>
    </div>
  </a-drawer>
</template>

<script>
import {defineComponent, reactive, toRefs, watch} from "vue";
import {PlusOutlined, QuestionCircleOutlined} from "@ant-design/icons-vue";
import request from "../../../../common/utils/request";
import {Form, message} from "ant-design-vue";
import {TextTip} from "bl-common-vue3";

const useForm = Form.useForm;

export default defineComponent({
  name: "PreStoreSettingEdit",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: Number,
      default: 0,
    },
  },
  components: {PlusOutlined, TextTip, QuestionCircleOutlined},
  setup(props, context) {
    const state = reactive({
      costTypeList: [],
      addValue: "",
      addVisible: false,
      detail: {},

      tagList: [],
      addCostVisible: false,

      text: 1,
      common_charge: 1,
      cost_list: [],
      xiangmlist: [],
    });

    const StatusChange = (val) => {
      if (state.common_charge == 0 && val == 0) {
        state.text = 1;
        message.warning("通用预存和专项预存不能同时关闭！");
      } else {
        state.text = val;
        if (val == 0) {
          state.xiangmlist = [];
        }
      }
    };

    const StatusChanges = (val) => {
      if (state.text == 0 && val == 0) {
        state.common_charge = 1;
        message.warning("通用预存和专项预存不能同时关闭！");
      } else {
        state.common_charge = val;
      }
    };

    const modelRef = reactive({
      cost_types: [],
      recharge_item: [],
      can_customize: false,
    });
    const ruleRef = reactive({});
    const {resetFields, validate, validateInfos} = useForm(modelRef, ruleRef);

    const addConfirm = () => {
      const existIndex = modelRef.recharge_item.findIndex(
          (item) => item == state.addValue
      );
      if (existIndex === -1) {
        modelRef.recharge_item.push(state.addValue);
        sortRechargeItem();
        state.addValue = "";
        state.addVisible = false;
      } else {
        message.warning("该金额已经添加！");
      }
    };

    const sortRechargeItem = () => {
      return modelRef.recharge_item.sort((a, b) => Number(a) - Number(b));
    };

    const onChargeItemRemove = (index) => {
      modelRef.recharge_item.splice(index, 1);
    };

    const onCancel = () => {
      context.emit("cancel");
    };

    const onSubmit = () => {
      if (state.text == 1 && state.common_charge == 0) {
        if (state.xiangmlist && state.xiangmlist.length == 0) {
          message.warning("专项预存至少选择一个类型！");
          return;
        }
      }

      validate().then(() => {
        let params = {
          id: props.id,
          ...modelRef,
          needMsg: true,
          // single_open: state.text,
          // common_charge: state.common_charge,
          // single_info: [],
        };
        delete params.cost_types
        // if (state.tagList.length > 0) {
        //   state.tagList.forEach((item) => {
        //     params.cost_types.push(item.value);
        //   });
        // }
        //
        // if (state.xiangmlist.length > 0) {
        //   state.xiangmlist.forEach((item) => {
        //     params.single_info.push(item.value);
        //   });
        // }
        request
            .put("/org", "/stream/prestoreEdit", {...params})
            .then((res) => {
              message.success(res.msg || "保存成功！");
              context.emit("success");
            });
      });
    };

    const getDetail = () => {
      request
          .get("/org", "/stream/prestoreDetail", {
            id: props.id,
          })
          .then((res) => {
            state.detail = res.detail;
            state.text = res.detail.single_open;
            state.common_charge = res.detail.common_charge;
            modelRef.can_customize = res.detail.can_customize == 1
            modelRef.recharge_item = state.detail.recharge_item || [];
            // if (state.detail.cost_types && state.detail.cost_types.length > 0) {
            //   request
            //       .post("/org", "/bill/getBillCostCategorys", {
            //         cost_types: state.detail.cost_types,
            //       })
            //       .then((result) => {
            //         // 反选
            //         if (result.costList && result.costList.length > 0) {
            //           result.costList.forEach((item) => {
            //             state.tagList.push({
            //               label: item.name,
            //               value: item.cost_type,
            //               cat_id: item.category_id,
            //             });
            //           });
            //         }
            //       });
            // }
            // if (state.detail.single_info && state.detail.single_info.length > 0) {
            //   request
            //       .post("/org", "/bill/getBillCostCategorys", {
            //         cost_types: state.detail.single_info,
            //       })
            //       .then((result) => {
            //         // 反选
            //         if (result.costList && result.costList.length > 0) {
            //           result.costList.forEach((item) => {
            //             state.xiangmlist.push({
            //               label: item.name,
            //               value: item.cost_type,
            //               cat_id: item.category_id,
            //             });
            //           });
            //         }
            //       });
            // }
          });
    };

    const getCostTypeList = () => {
      request.get("/org", "/bill/cost/categoryList", {}).then((res) => {
        if (res.list) {
          state.costTypeList = res.list.map((item) => ({
            label: item.name,
            value: item.id,
            isLeaf: false,
          }));
        }
      });
    };

    const getCostTypeSub = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      request
          .get("/org", "/bill/costList", {
            page: 1,
            limit: 9999,
            category_id: targetOption.value,
            status: 1,
          })
          .then((res) => {
            if (res.list) {
              targetOption.loading = false;
              targetOption.children = res.list.map((item) => ({
                label: item.name,
                value: item.cost_type,
                isLeaf: true,
              }));
              state.costTypeList = [...state.costTypeList];
            }
          });
    };

    const init = () => {
      getCostTypeList();
      getDetail();
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            init();
          } else {
            resetFields();
            state.tagList = [];
            state.xiangmlist = [];
          }
        }
    );

    const onCostTypeChange = (value, selectedOptions) => {
      let alreadyHave = state.tagList.find(
          (item) => item.cat_id == value[0] && item.value == value[1]
      );

      if (alreadyHave) {
        message.warn("已添加过该费用类型，无法重复添加");
      } else {
        state.tagList.push({
          label: selectedOptions[1].label,
          value: value[1],
          cat_id: value[0],
        });

        // // 给已选中项加禁用
        // state.costTypeList.forEach((cate) => {
        //   if (cate.value == value[0]) {
        //     cate.children.forEach((cost) => {
        //       if (cost.value == value[1]) {
        //         cost.disabled = true;
        //       }
        //     });
        //   }
        // });
        state.addCostVisible = false;
      }
      modelRef.cost_types = [];
    };

    const TypeChange = (value, selectedOptions) => {
      let alreadyHave = state.xiangmlist.find(
          (item) => item.cat_id == value[0] && item.value == value[1]
      );

      if (alreadyHave) {
        message.warn("已添加过该费用类型，无法重复添加");
      } else {
        state.xiangmlist.push({
          label: selectedOptions[1].label,
          value: value[1],
          cat_id: value[0],
        });
      }
      state.cost_list = [];
    };
    const removeCost = (tagItem, tagIndex) => {
      state.xiangmlist.splice(tagIndex, 1);
    };

    const removeCostType = (tagItem, tagIndex) => {
      state.tagList.splice(tagIndex, 1);

      // // 取消禁用
      // state.costTypeList.forEach((cate) => {
      //   if (cate.value == tagItem.cat_id) {
      //     cate.children.forEach((cost) => {
      //       if (cost.value == tagItem.value) {
      //         cost.disabled = false;
      //       }
      //     });
      //   }
      // });
    };

    return {
      modelRef,
      ...toRefs(state),
      onCancel,
      onSubmit,
      addConfirm,
      onChargeItemRemove,
      getCostTypeSub,
      onCostTypeChange,
      removeCostType,
      StatusChange,
      StatusChanges,
      TypeChange,
      removeCost,
    };
  },
});
</script>
<style lang="less" scoped>
.becurrent {
  width: 100px;
  padding-top: 10px;
  padding-bottom: 6px;
  text-align: center;
  background-color: #ececec;
  display: inline-block;
  border-radius: 10px 10px 0px 0px;
}
</style>
